<?php

namespace pc\models;

use common\Service\RedisService;
use Yii;
use common\models\News as P_News;

class News extends P_News
{

    /*
     * 入库是处理文章 替换图片链接 以及 干掉内容中的外链
     */
    public function dealArticle(){
        $news = News::find()->where(['in_redis'=>0])->limit(500)->asArray()->all();
        foreach ($news as &$new){
            $new['images'] = json_decode($new['images'],true);
            preg_match_all('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$new['content'],$imgs);
            if($imgs[0]){
                foreach ($imgs[0] as $key=>$img){
                    $temp = "<img alt='{$new['title']}' src='{$new['images'][$key]['img']}' style='max-width: 100%;height:auto;'>";
                    $new['content'] = str_replace($img,$temp,$new['content']);
                }

            }
            foreach ($new['images'] as &$vo){
                $vo['image'] = Yii::$app->params['ImageDomain'].'/article/'.$new['id'].'/'.explode('/',$vo['img'])[5];
                $new['content'] = str_replace($vo['img'],$vo['image'],$new['content']);
                $vo['img'] = $vo['image'];
                unset($vo['image']);
            }unset($vo);
            $new['content'] = preg_replace("#<a[^>]*>(.*?)</a>#is", "$1", $new['content']);
            $new['images'] = json_encode($new['images']);
            $new['in_redis'] = 0;
            $model = News::findOne($new['id']);
            $model->setAttributes($new);
            $model->save();
        }


        print_r($news);
    }

    /**
     * @desc 把正式的新闻数据放入redis 临时处理
     */
    public function setRedis(){
        $news = News::find()->where(['in_redis'=>1])->limit(500)->orderBy('id desc')->asArray()->all();
        foreach ($news as $new){
            $this->setInfoToRedis($new['id'],$new);
            $model = News::findOne($new['id']);
            $model->setAttribute('in_redis',2);
            $model->save();
        }
    }

    //TODO 待完善
    public static function getStarNews($limit = 4,$fields = []){
        $newIds = [666,667,668,690,700,670,688,678,679,688,700];
        $rs = [];
        $newIdsIndex = array_rand($newIds,4);
        foreach ($newIdsIndex as $index){
            $newInfo = static::getNewsInfoById($newIds[$index],$fields);
            $newInfo && $rs[] = $newInfo;
        }
        return $rs;
    }

}
